/*
 * @Descripttion: 
 * @version: 
 * @Author: turingchang
 * @Date: 2020-12-16 17:43:44
 * @LastEditors: turingchang
 * @LastEditTime: 2020-12-17 15:49:36
 */

"use strict";

const fetch = require("node-fetch");
const enums = require("../../enum/enums");
const utils = require("../../common/utils");

class Mobpush{
  constructor(appkey, appSecret) {
    this.appkey = appkey;
    this.appSecret = appSecret;
  //   if (!this.appkey) {
  //     throw new Error("appkey不能为空");
  //   }
  //   if (!this.appSecret) {
  //     throw new Error("appSecret不能为空");
  //   }
    this.defaultObj = {
      appkey: appkey,
      appSecret: appSecret,
    };
  }

  /**
   *
   * 公用请求方法
   * @param {*} url
   * @param {*} data
   * @returns {Promise}
   * @memberof API
   */
  async request(url, data) {
    let requestUrl = enums.mobpush_api_url.prefix.value + url,
      assignData = Object.assign(this.defaultObj, data);
    const response = await fetch(requestUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        sign: utils.md5.md5(JSON.stringify(assignData) + this.appSecret),
        key: this.appkey,
      },
      body: JSON.stringify(assignData),
    });
    return this.checkStatus(response);
  }

  /**
   * 处理接口返回
   *
   * @param {*} response
   * @returns
   * @memberof API
   */
  checkStatus(response) {
    return response.json();
  }    
}

Mobpush.mixin = function (obj) {
  for (var key in obj) {
    if (Mobpush.prototype.hasOwnProperty(key)) {      
      // console.log(1111,key);
      // throw new Error(
      //   "Don't allow override existed prototype method. method: " + key
      // );
      continue;
    }    
    Mobpush.prototype[key] = obj[key];
  }
};

module.exports = Mobpush;

